package com.hhh.Filter;

import com.alibaba.fastjson2.JSON;
import com.hhh.Pojo.Result;
import com.hhh.Util.GetThreadNow;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;


//要在启动类上加载@ServletComponentScan注解
@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {

    //     url匹配器
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
//    你也可以写正则表达式去匹配，上一个项目就是这么写的
    /*
     private String regex = "/login";
      //判断URL是否是login
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(Url);
        String regexarr = "";
        while (matcher.find())
            regexarr = matcher.group();
        if (regexarr.length() != 0) {
            //是
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    */


    //    可以放行的url
    private static final String[] urlarr = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/user/login"
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        获取请求的url
        HttpServletRequest hSRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse hSResponse = (HttpServletResponse) servletResponse;
        String str = String.valueOf(hSRequest.getRequestURL());
        String url = "/" + str.split("/", 4)[3];
//        匹配url
        for (String checkurl : urlarr) {
//            如果不需要处理，放行
            if (ANT_PATH_MATCHER.match(checkurl, url) == true) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
//        需要处理
//        判断是否登录
//        未登录
        if (hSRequest.getSession().getAttribute("employee") != null) {
//            已登录
//        获取线程里的updateUser Id
            long id = (Long) hSRequest.getSession().getAttribute("employee");
            GetThreadNow.SetIdInSession(id);
            filterChain.doFilter(hSRequest, hSResponse);
            return;
        } else if (hSRequest.getSession().getAttribute("user") != null) {
//            已登录
//        获取线程里的updateUser Id
            long id = (Long) hSRequest.getSession().getAttribute("user");
            GetThreadNow.SetIdInSession(id);
            filterChain.doFilter(hSRequest, hSResponse);
            return;
        }

        log.info("拦截到的请求：" + str);

        String notlogin = JSON.toJSONString(Result.error("NOTLOGIN"));
        hSResponse.getWriter().write(notlogin);
//            关流
        hSResponse.getWriter().close();
    }
}
